package com.xzw.cameratest.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.UUID;


public class SPUtils {

    private final static String name = "dahuatech";
    private final static int mode = Context.MODE_PRIVATE;
    private static Context sContext;

    public static void init(Context context) {
        sContext = context;
    }

    /**
     * 保存首选项
     *
     * @param key
     * @param value
     */
    public static boolean saveBoolean(String key, boolean value) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        Editor edit = sp.edit();
        key = encodeString(key);
        edit.putBoolean(key, value);
        return edit.commit();
    }


    public static boolean saveInt(String key, int value) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        Editor edit = sp.edit();
        key = encodeString(key);
        edit.putInt(key, value);
        return edit.commit();
    }

    public static boolean saveString(String key, String value) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        Editor edit = sp.edit();
        key = encodeString(key);
        value = encodeString(value);
        edit.putString(key, value);
        return edit.commit();
    }


    /**
     * 获取首选项
     *
     * @param key
     * @param defValue
     * @return
     */
    public static boolean getBoolean(String key, boolean defValue) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        key = encodeString(key);
        return sp.getBoolean(key, defValue);
    }

    public static int getInt(String key, int defValue) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        key = encodeString(key);
        return sp.getInt(key, defValue);
    }

    public static String getString(String key, String defValue) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        key = encodeString(key);
        defValue = encodeString(defValue);
        String value = sp.getString(key, defValue);
        return decodeString(value);
    }


    //初级加密相关

    private static String encodeString(String str) {
        if (str == null) {
            return null;
        }
        byte[] bytes = str.getBytes();
        byte[] encrypt = encrypt(bytes, getStringKey());
        return Base64.encodeToString(encrypt, Base64.DEFAULT).trim();
    }

    private static String decodeString(String str) {
        if (str == null) {
            return null;
        }
        byte[] decode = Base64.decode(str, Base64.DEFAULT);
        byte[] encrypt = encrypt(decode, getStringKey());
        return new String(encrypt);
    }

    private static int getStringKey() {
        String uuid = getUUID();
        byte[] bytes = uuid.getBytes();
        int key = 1;
        for (byte aByte : bytes) {
            key += aByte;
        }
        return key;
    }


    private static byte[] encrypt(byte[] bytes, int key) {
        if (bytes == null) {
            return null;
        }
        int len = bytes.length;
        for (int i = 0; i < len; i++) {
            bytes[i] ^= key;
        }
        return bytes;
    }

    //制作一个uuid
    private static String sID = null;
    private static final String KEY_UUID = "UUID";

    public synchronized static String getUUID() {
        if (sID == null) {
            sID = getUUID(KEY_UUID, "");
            if (TextUtils.isEmpty(sID)) {
                sID = UUID.randomUUID().toString();
                for (int i = 0; i < 8; i++) {
                    if (saveUUID(KEY_UUID, sID)) {
                        break;
                    }
                }
            }
        }
        return sID;
    }

    private static String getUUID(String key, String defValue) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        return sp.getString(key, defValue);
    }

    private static boolean saveUUID(String key, String value) {
        SharedPreferences sp = sContext.getSharedPreferences(name, mode);
        Editor edit = sp.edit();
        edit.putString(key, value);
        return edit.commit();
    }

    /**
     * 保存对象
     */
    public static boolean putObject(String key, Object object) {
        SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(sContext);
        if (object == null) {
            Editor editor = share.edit().remove(key);
            return editor.commit();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // 将对象放到OutputStream中
        // 将对象转换成byte数组，并将其进行base64编码
        String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
        try {
            baos.close();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Editor editor = share.edit();
        // 将编码后的字符串写到base64.xml文件中
        editor.putString(key, objectStr);
        return editor.commit();
    }

    /**
     * 获取对象
     */
    public static Object getObject(String key) {
        SharedPreferences sharePre = PreferenceManager
                .getDefaultSharedPreferences(sContext);
        try {
            String wordBase64 = sharePre.getString(key, "");
            // 将base64格式字符串还原成byte数组
            if (wordBase64.equals("")) { // 不可少，否则在下面会报java.io.StreamCorruptedException
                return null;
            }
            byte[] objBytes = Base64.decode(wordBase64.getBytes(),
                    Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            // 将byte数组转换成product对象
            Object obj = ois.readObject();
            bais.close();
            ois.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
